package controller

import (
	"encoding/json"
	"fmt"
	"log/slog"
	"quick-go/pkg"
	"quick-go/cache"
    "quick-go/model"
	"github.com/gin-gonic/gin"
)

type OrderController struct{}

type OrderParam struct {
	Oid   int    `json:"id"` // 前端请求的参数是 id，后端接收的参数是 Oid
	Oname string `json:"name"`
}

func (o OrderController) GetOrderOneRedis(c *gin.Context) {
	oid := c.Param("Oid")
	oname := c.Param("Oname")
	redisKey := fmt.Sprintf("order:%s", oname)

	// 1. 先查 Redis
	rs, err := cache.Rdb.Get(cache.Rctx, redisKey).Result()
	if err == nil && rs != "" {
		// 命中缓存，直接返回
		ReturnSuccess(c, 200, "success (from redis)", rs, 1)
		return
	}

	// 2. 查数据库
	rsDb, errDb := model.GetOrderByID(oid)
	if errDb != nil {
		ReturnError(c, 4001, "order list error")
		return
	}

	// 3. 写入 Redis，设置过期时间
	jsonData, _ := json.Marshal(rsDb)
	cache.Rdb.Set(cache.Rctx, redisKey, jsonData, 60*30) // 30 minutes后过期

	ReturnSuccess(c, 200, "success", rsDb, 1)
}

func (o OrderController) GetOrderOne(c *gin.Context) {
	pkg.Logger.Info("GetOrderOne called",
		slog.String("handler", "GetOrderOne"),
		slog.String("client_ip", c.ClientIP()),
	)

	// oid := c.PostForm("id")
	// oid := c.DefaultPostForm("id", "1") // 如果 id 为空，则默认为 1
	ReturnSuccess(c, 200, "id", "order id", 1)
}

func (o OrderController) GetOrderList(c *gin.Context) {
	pkg.Logger.Debug("GetOrderList request received",
		slog.Any("headers", c.Request.Header),
	)

	OrderParam := &OrderParam{}
	if err := c.BindJSON(OrderParam); err != nil {
		pkg.Logger.Error("BindJSON failed",
			slog.String("error", err.Error()),
			slog.Any("request_body", c.Request.Body),
		)
		ReturnError(c, 4001, "order list error")
		return
	}

	pkg.Logger.Info("Order processed",
		slog.Int("order_id", OrderParam.Oid),
		slog.String("order_name", OrderParam.Oname),
	)

	ReturnSuccess(c, 200, OrderParam.Oid, OrderParam.Oname, 1)
}
